/********************************************************************************
* Project       : No Latency RTSP streaming Project
* Author        : Seo, SeokWon 
* e-mail        : kueony@gmail.com
* Licence       : See the Copyright
*********************************************************************************/

#include <stdlib.h>
#include <unistd.h>

#include "lib_common.h"

#define LIB_COMMON_STACK_SIZE_1K	1024

int InitDaemon()
{
    pid_t pid;

    if((pid = fork()) < 0) return -1;
    else if(pid > 0) exit(0);

//	close(2);   //close stderr
//	close(1);   //close stdout
    setsid();

    return pid;
}


int ForkAndExec(char **a_ppcArg)
{
    int     pid;

    pid = fork();

    if(pid < 0)
    {
        return -1;
    }
    else if(pid == 0)
    {
//      close(0);
//      close(1);
		setsid();
        if(execvp(a_ppcArg[0], a_ppcArg) == -1)
        {
            exit(0);
        }
    }

    return 0;
}



/*
int	GetThreadMinStackSize()
{
	pthread_attr_t Thread_Attr;
	int	l_iStackSize = 0;

    pthread_attr_init(&Thread_Attr);

	if(pthread_attr_getstacksize(&Thread_Attr, (size_t *) &l_iStackSize) < 0)
	{
		return -1;
	}

	do
	{
		l_iStackSize -= LIB_COMMON_STACK_SIZE_1K;
	} while(pthread_attr_setstacksize(&Thread_Attr, l_iStackSize) == 0);

	l_iStackSize += LIB_COMMON_STACK_SIZE_1K;

	return l_iStackSize;
}


int GetThreadProperStackSize(int a_iSize)
{
	pthread_attr_t Thread_Attr;
	int	l_iStackSize = 0;

    pthread_attr_init(&Thread_Attr);

	if(pthread_attr_setstacksize(&Thread_Attr, a_iSize) == 0)
	{
		return a_iSize;
	}

	if(pthread_attr_getstacksize(&Thread_Attr, (size_t *) &l_iStackSize) < 0)
	{
		return -1;
	}

	if(a_iSize == l_iStackSize)
	{
		return a_iSize;
	}
	else if(a_iSize < l_iStackSize) 
	{
		l_iStackSize = a_iSize;
		do
		{
			l_iStackSize += LIB_COMMON_STACK_SIZE_1K;
		} while(pthread_attr_setstacksize(&Thread_Attr, l_iStackSize) != 0);
	}
	else
	{
		l_iStackSize = a_iSize;
		do
		{
			l_iStackSize -= LIB_COMMON_STACK_SIZE_1K;
		} while(pthread_attr_setstacksize(&Thread_Attr, l_iStackSize) != 0);
	}

	return l_iStackSize;
}
*/
